package com.hatricks.is.redission.configuration;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.hatricks.is.redission.ILockKeyEnum;
import com.hatricks.is.redission.KeyLock;
import com.hatricks.is.redission.distributedlock.DistributedKeyLock;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJndi;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class RedissonConfiguration {


    private static final String REDIS_PREFIX = "redis://";


    @Bean(destroyMethod = "shutdown")
    RedissonClient redissonClient(RedisProperties properties) {
        Config config = new Config();
        RedisProperties.Cluster cluster = properties.getCluster();
        if (cluster == null) {
            config.useSingleServer().setAddress(REDIS_PREFIX + properties.getHost() + ":" + properties.getPort());
            if (StrUtil.isNotEmpty(properties.getPassword())) {
                config.useSingleServer().setPassword(properties.getPassword());
            }
            config.useSingleServer().setDatabase(properties.getDatabase());
            return Redisson.create(config);
        }
        List<String> nodes = cluster.getNodes();
        String[] arrays = ArrayUtil.newArray(String.class, nodes.size());
        for (int i = 0; i < nodes.size(); i++) {
            arrays[i] = REDIS_PREFIX + nodes.get(i);
        }
        ClusterServersConfig sc = config.useClusterServers();
        sc.addNodeAddress(arrays).setPassword(properties.getPassword());
        return Redisson.create(config);
    }

    @Bean(value = "HOST_KEY_LOCK")
    public KeyLock<ILockKeyEnum> lockFactory(RedissonClient redissonClient) {
        return new DistributedKeyLock<>(redissonClient);
    }
}
